/**
 * 营销自动化服务
 * 提供内容分发、多平台数据管理和效果分析功能
 */

import { get, post } from '@/utils/request';
import { handleError } from '@/utils/errorHandler';
import { cache } from '@/utils/cacheManager';
import { douyinService } from './douyinService';
import { xiaohongshuService } from './xiaohongshuService';

// 平台类型枚举
enum Platform {
  DOUYIN = 'douyin',
  XIAOHONGSHU = 'xiaohongshu',
  WECHAT = 'wechat',
  WEIBO = 'weibo'
}

// 内容类型接口
interface Content {
  id: string;
  title: string;
  description: string;
  type: 'image' | 'video' | 'text';
  media_urls: string[];
  tags: string[];
  topics: string[];
  target_audience: string[];
  created_at: string;
  updated_at: string;
}

// 发布任务接口
interface PublishTask {
  id: string;
  content_id: string;
  platforms: Platform[];
  schedule_time?: number;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  results: PublishResult[];
  created_at: string;
}

// 发布结果接口
interface PublishResult {
  platform: Platform;
  success: boolean;
  post_id?: string;
  error_message?: string;
  published_at?: string;
}

// 营销活动接口
interface Campaign {
  id: string;
  name: string;
  description: string;
  start_date: string;
  end_date: string;
  target_platforms: Platform[];
  content_ids: string[];
  budget: number;
  status: 'draft' | 'active' | 'paused' | 'completed';
  metrics: CampaignMetrics;
}

// 活动指标接口
interface CampaignMetrics {
  total_reach: number;
  total_engagement: number;
  total_clicks: number;
  total_conversions: number;
  cost_per_click: number;
  conversion_rate: number;
  roi: number;
}

// 用户画像接口
interface UserProfile {
  user_id: string;
  demographics: {
    age_range: string;
    gender: string;
    location: string;
    income_level: string;
  };
  interests: string[];
  behavior: {
    active_hours: string[];
    preferred_content_types: string[];
    engagement_rate: number;
  };
  platform_preferences: {
    [key in Platform]?: {
      usage_frequency: number;
      engagement_score: number;
    };
  };
}

// 内容推荐接口
interface ContentRecommendation {
  content_type: string;
  optimal_time: string;
  suggested_tags: string[];
  trending_topics: string[];
  target_audience: string[];
  estimated_reach: number;
  confidence_score: number;
}

// 分析报告接口
interface AnalyticsReport {
  period: string;
  platform_performance: {
    [key in Platform]?: {
      posts_count: number;
      total_reach: number;
      total_engagement: number;
      engagement_rate: number;
      top_performing_content: string[];
    };
  };
  audience_insights: {
    demographics: any;
    interests: string[];
    behavior_patterns: any;
  };
  content_performance: {
    best_performing_types: string[];
    optimal_posting_times: string[];
    trending_topics: string[];
  };
  recommendations: string[];
}

/**
 * 营销自动化服务类
 */
class MarketingAutomationService {
  private publishQueue: PublishTask[] = [];
  private campaigns: Map<string, Campaign> = new Map();
  private userProfiles: Map<string, UserProfile> = new Map();
  
  constructor() {
    this.loadData();
    this.startQueueProcessor();
  }
  
  /**
   * 加载本地数据
   */
  private loadData(): void {
    try {
      const queueData = cache.get('publish_queue', 'local');
      if (queueData) {
        this.publishQueue = queueData as PublishTask[];
      }
      
      const campaignsData = cache.get('campaigns', 'local');
      if (campaignsData) {
        this.campaigns = new Map(campaignsData as [string, Campaign][]);
      }
      
      const profilesData = cache.get('user_profiles', 'local');
      if (profilesData) {
        this.userProfiles = new Map(profilesData as [string, UserProfile][]);
      }
    } catch (error) {
      console.warn('Failed to load marketing automation data:', error);
    }
  }
  
  /**
   * 保存数据到本地存储
   */
  private saveData(): void {
    try {
      cache.set('publish_queue', this.publishQueue, {
        storage: 'local',
        expireTime: 24 * 60 * 60 * 1000 // 24小时
      });
      
      cache.set('campaigns', Array.from(this.campaigns.entries()), {
        storage: 'local',
        expireTime: 24 * 60 * 60 * 1000
      });
      
      cache.set('user_profiles', Array.from(this.userProfiles.entries()), {
        storage: 'local',
        expireTime: 24 * 60 * 60 * 1000
      });
    } catch (error) {
      console.error('Failed to save marketing automation data:', error);
    }
  }
  
  /**
   * 创建内容
   */
  async createContent(contentData: Omit<Content, 'id' | 'created_at' | 'updated_at'>): Promise<Content> {
    try {
      const content: Content = {
        id: this.generateId(),
        ...contentData,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      // 保存到后端
      await post('/api/marketing/content', content);
      
      return content;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 创建发布任务
   */
  async createPublishTask(contentId: string, platforms: Platform[], scheduleTime?: number): Promise<PublishTask> {
    try {
      const task: PublishTask = {
        id: this.generateId(),
        content_id: contentId,
        platforms: platforms,
        schedule_time: scheduleTime,
        status: 'pending',
        results: [],
        created_at: new Date().toISOString()
      };
      
      this.publishQueue.push(task);
      this.saveData();
      
      return task;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 批量发布内容到多个平台
   */
  async batchPublish(contentId: string, platforms: Platform[]): Promise<PublishResult[]> {
    try {
      const content = await this.getContent(contentId);
      const results: PublishResult[] = [];
      
      for (const platform of platforms) {
        try {
          const result = await this.publishToPlatform(content, platform);
          results.push(result);
        } catch (error) {
          results.push({
            platform,
            success: false,
            error_message: error instanceof Error ? error.message : 'Unknown error'
          });
        }
      }
      
      return results;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 发布内容到指定平台
   */
  private async publishToPlatform(content: Content, platform: Platform): Promise<PublishResult> {
    try {
      let postId: string;
      
      switch (platform) {
        case Platform.DOUYIN:
          const douyinResult = await douyinService.publishVideo({
            video_url: content.media_urls[0],
            text: `${content.title}\n${content.description}`
          });
          postId = douyinResult.item_id;
          break;
          
        case Platform.XIAOHONGSHU:
          const xhsResult = await xiaohongshuService.publishNote({
            title: content.title,
            desc: content.description,
            type: content.type === 'video' ? 'video' : 'normal',
            images: content.type === 'image' ? content.media_urls : undefined,
            video_url: content.type === 'video' ? content.media_urls[0] : undefined,
            tags: content.tags
          });
          postId = xhsResult.note_id;
          break;
          
        default:
          throw new Error(`Unsupported platform: ${platform}`);
      }
      
      return {
        platform,
        success: true,
        post_id: postId,
        published_at: new Date().toISOString()
      };
    } catch (error) {
      return {
        platform,
        success: false,
        error_message: error instanceof Error ? error.message : 'Unknown error'
      };
    }
  }
  
  /**
   * 获取内容详情
   */
  private async getContent(contentId: string): Promise<Content> {
    try {
      const response = await get(`/api/marketing/content/${contentId}`);
      return response.data;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 创建营销活动
   */
  async createCampaign(campaignData: Omit<Campaign, 'id' | 'metrics'>): Promise<Campaign> {
    try {
      const campaign: Campaign = {
        id: this.generateId(),
        ...campaignData,
        metrics: {
          total_reach: 0,
          total_engagement: 0,
          total_clicks: 0,
          total_conversions: 0,
          cost_per_click: 0,
          conversion_rate: 0,
          roi: 0
        }
      };
      
      this.campaigns.set(campaign.id, campaign);
      this.saveData();
      
      // 保存到后端
      await post('/api/marketing/campaigns', campaign);
      
      return campaign;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取营销活动列表
   */
  getCampaigns(): Campaign[] {
    return Array.from(this.campaigns.values());
  }
  
  /**
   * 更新活动指标
   */
  async updateCampaignMetrics(campaignId: string): Promise<void> {
    try {
      const campaign = this.campaigns.get(campaignId);
      if (!campaign) {
        throw new Error('Campaign not found');
      }
      
      // 获取各平台数据
      const metrics = await this.calculateCampaignMetrics(campaign);
      
      campaign.metrics = metrics;
      this.campaigns.set(campaignId, campaign);
      this.saveData();
      
      // 更新后端数据
      await post(`/api/marketing/campaigns/${campaignId}/metrics`, metrics);
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 计算活动指标
   */
  private async calculateCampaignMetrics(campaign: Campaign): Promise<CampaignMetrics> {
    try {
      let totalReach = 0;
      let totalEngagement = 0;
      let totalClicks = 0;
      let totalConversions = 0;
      
      // 从各平台获取数据
      for (const platform of campaign.target_platforms) {
        const platformMetrics = await this.getPlatformMetrics(platform, campaign.content_ids);
        totalReach += platformMetrics.reach;
        totalEngagement += platformMetrics.engagement;
        totalClicks += platformMetrics.clicks;
        totalConversions += platformMetrics.conversions;
      }
      
      const costPerClick = totalClicks > 0 ? campaign.budget / totalClicks : 0;
      const conversionRate = totalClicks > 0 ? (totalConversions / totalClicks) * 100 : 0;
      const roi = campaign.budget > 0 ? ((totalConversions * 100 - campaign.budget) / campaign.budget) * 100 : 0;
      
      return {
        total_reach: totalReach,
        total_engagement: totalEngagement,
        total_clicks: totalClicks,
        total_conversions: totalConversions,
        cost_per_click: costPerClick,
        conversion_rate: conversionRate,
        roi: roi
      };
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取平台指标数据
   */
  private async getPlatformMetrics(platform: Platform, contentIds: string[]): Promise<{
    reach: number;
    engagement: number;
    clicks: number;
    conversions: number;
  }> {
    try {
      const response = await get('/api/marketing/platform-metrics', {
        platform,
        content_ids: contentIds
      });
      
      return response.data;
    } catch (error) {
      // 返回默认值
      return {
        reach: 0,
        engagement: 0,
        clicks: 0,
        conversions: 0
      };
    }
  }
  
  /**
   * 生成内容推荐
   */
  async generateContentRecommendations(userId: string, targetPlatforms: Platform[]): Promise<ContentRecommendation[]> {
    try {
      const userProfile = this.userProfiles.get(userId);
      const recommendations: ContentRecommendation[] = [];
      
      for (const platform of targetPlatforms) {
        const recommendation = await this.getContentRecommendationForPlatform(platform, userProfile);
        recommendations.push(recommendation);
      }
      
      return recommendations;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 获取平台内容推荐
   */
  private async getContentRecommendationForPlatform(
    platform: Platform, 
    userProfile?: UserProfile
  ): Promise<ContentRecommendation> {
    try {
      const response = await post('/api/marketing/content-recommendations', {
        platform,
        user_profile: userProfile
      });
      
      return response.data;
    } catch (error) {
      // 返回默认推荐
      return {
        content_type: 'video',
        optimal_time: '19:00-21:00',
        suggested_tags: ['母婴', '育儿', '好物推荐'],
        trending_topics: ['新手妈妈必备', '宝宝辅食'],
        target_audience: ['25-35岁女性'],
        estimated_reach: 10000,
        confidence_score: 0.7
      };
    }
  }
  
  /**
   * 生成分析报告
   */
  async generateAnalyticsReport(period: string, platforms: Platform[]): Promise<AnalyticsReport> {
    try {
      const cacheKey = `analytics_report_${period}_${platforms.join(',')}`;
      
      return await cache.getOrSet(
        cacheKey,
        async () => {
          const response = await post('/api/marketing/analytics-report', {
            period,
            platforms
          });
          
          return response.data;
        },
        {
          storage: 'local',
          expireTime: 60 * 60 * 1000 // 1小时
        }
      );
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 同步多平台数据
   */
  async syncPlatformData(): Promise<void> {
    try {
      const platforms = [Platform.DOUYIN, Platform.XIAOHONGSHU];
      
      for (const platform of platforms) {
        await this.syncSinglePlatformData(platform);
      }
      
      console.log('All platform data synced successfully');
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
  
  /**
   * 同步单个平台数据
   */
  private async syncSinglePlatformData(platform: Platform): Promise<void> {
    try {
      switch (platform) {
        case Platform.DOUYIN:
          // 同步抖音数据
          const douyinUser = await douyinService.getUserInfo();
          await douyinService.syncUserData(douyinUser.open_id);
          break;
          
        case Platform.XIAOHONGSHU:
          // 同步小红书数据
          const xhsUser = await xiaohongshuService.getUserInfo();
          await xiaohongshuService.syncUserData(xhsUser.user_id);
          break;
      }
    } catch (error) {
      console.error(`Failed to sync ${platform} data:`, error);
    }
  }
  
  /**
   * 启动队列处理器
   */
  private startQueueProcessor(): void {
    setInterval(() => {
      this.processPublishQueue();
    }, 60000); // 每分钟检查一次
  }
  
  /**
   * 处理发布队列
   */
  private async processPublishQueue(): Promise<void> {
    const now = Date.now();
    
    for (const task of this.publishQueue) {
      if (task.status === 'pending') {
        // 检查是否到了发布时间
        if (!task.schedule_time || task.schedule_time <= now) {
          task.status = 'processing';
          
          try {
            const results = await this.batchPublish(task.content_id, task.platforms);
            task.results = results;
            task.status = 'completed';
          } catch (error) {
            task.status = 'failed';
            console.error('Failed to process publish task:', error);
          }
        }
      }
    }
    
    // 清理已完成的任务（保留7天）
    const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000;
    this.publishQueue = this.publishQueue.filter(task => {
      const taskTime = new Date(task.created_at).getTime();
      return taskTime > sevenDaysAgo || task.status === 'pending' || task.status === 'processing';
    });
    
    this.saveData();
  }
  
  /**
   * 获取发布任务状态
   */
  getPublishTaskStatus(taskId: string): PublishTask | null {
    return this.publishQueue.find(task => task.id === taskId) || null;
  }
  
  /**
   * 获取发布队列
   */
  getPublishQueue(): PublishTask[] {
    return this.publishQueue;
  }
  
  /**
   * 生成唯一ID
   */
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }
  
  /**
   * 获取平台统计数据
   */
  async getPlatformStats(): Promise<{
    [key in Platform]?: {
      connected: boolean;
      posts_count: number;
      followers: number;
      engagement_rate: number;
    };
  }> {
    try {
      const stats: any = {};
      
      // 抖音统计
      try {
        const douyinStats = await douyinService.getAccountStats();
        stats[Platform.DOUYIN] = {
          connected: true,
          posts_count: douyinStats.aweme_count,
          followers: douyinStats.follower_count,
          engagement_rate: 0.05 // 示例数据
        };
      } catch (error) {
        stats[Platform.DOUYIN] = {
          connected: false,
          posts_count: 0,
          followers: 0,
          engagement_rate: 0
        };
      }
      
      // 小红书统计
      try {
        const xhsStats = await xiaohongshuService.getAccountStats();
        stats[Platform.XIAOHONGSHU] = {
          connected: true,
          posts_count: xhsStats.notes,
          followers: xhsStats.fans,
          engagement_rate: 0.08 // 示例数据
        };
      } catch (error) {
        stats[Platform.XIAOHONGSHU] = {
          connected: false,
          posts_count: 0,
          followers: 0,
          engagement_rate: 0
        };
      }
      
      return stats;
    } catch (error) {
      handleError(error, {
        showToast: true,
        logToConsole: true
      });
      throw error;
    }
  }
}

// 创建单例实例
const marketingAutomationService = new MarketingAutomationService();

// 导出服务实例和类型
export { marketingAutomationService, MarketingAutomationService, Platform };
export type { 
  Content, 
  PublishTask, 
  PublishResult, 
  Campaign, 
  CampaignMetrics, 
  UserProfile, 
  ContentRecommendation, 
  AnalyticsReport 
};

// 便捷方法导出
export const {
  createContent,
  createPublishTask,
  batchPublish,
  createCampaign,
  getCampaigns,
  updateCampaignMetrics,
  generateContentRecommendations,
  generateAnalyticsReport,
  syncPlatformData,
  getPublishTaskStatus,
  getPublishQueue,
  getPlatformStats
} = marketingAutomationService;

export default marketingAutomationService;